//
//  CashierNewViewController.m
//  TryShopping
//
//  Created by LiYinDi on 16/6/3.
//  Copyright © 2016年 RuiBen. All rights reserved.
//

#import "CashierNewViewController.h"
#import "HasSpecFmdbTool.h"
#import "NoSpecFmdbTool.h"
#import "HasSpecFmdbModel.h"
#import "NoSpecFmdbModel.h"
#import "CashierNewDataModel.h"
#import "SelectedGoodNewViewController.h"
#import "CashierNewPopView.h"
#import "CashierNewSearchViewController.h"
#import "RapidCashierViewController.h"
#import "GatheringListViewController.h"
#import "PlaceOrderViewController.h"
#import "OrderExtAddViewController.h"
#import "MembershipDetailsViewController.h"
#import "OrderDetailViewController.h"
#import "fmDataModel.h"
#import "WhsInAddViewController.h"
#import "StockManagementViewController.h"
#import "MemberListViewController.h"
#import "OrderListViewController.h"
#import "ToBindCompanyViewController.h"
#import "MsgPlaySound.h"
#import <AudioToolbox/AudioToolbox.h>
#import "MCouponBViewController.h"
#import "BusinessCheckVouchContinueViewController.h"
//#import "GatherSingleViewController.h"
#import "ReabamSingleton.h"
#import "SelectedGoodNewViewController1.h"
@interface CashierNewViewController ()<CashierNewPopViewDelegate,CashierNewSearchDelegate,MCouponBViewControllerDelegate>
{
    
    NSString *Token;
    CashierNewDataModel *cashierModel;
    NSString *titleStr;
    NSString *scanTypeStr;
    NSString*specIdStr;
    NSMutableArray*scanConponResultArray;
    NSMutableArray*snList;
    NSString * result1;
    ReabamSingleton*commdity;
}
@property (retain, nonatomic) UIAlertView* alt;
@end

@implementation CashierNewViewController

-(void)viewDidLoad
{
    
    [super viewDidLoad];
    scanConponResultArray=[[NSMutableArray alloc]init];
    snList=[[NSMutableArray alloc]init];

}

-(void)update:(NSString *)updateData{
    [scanConponResultArray removeAllObjects];
    [snList removeAllObjects];
    scanConponResultArray=[[NSMutableArray alloc]init];
    snList=[[NSMutableArray alloc]init];

}
-(void)viewWillAppear:(BOOL)animated
{
    commdity=[ReabamSingleton shared];
    self.memberDict=commdity.dataMemberDict;
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    if ([[user objectForKey:@"userStatus"] isEqualToString:@"E"]) {
        ToBindCompanyViewController * Login=[[ToBindCompanyViewController alloc]init];
        Login.viewSat=@"";
        [self.navigationController pushViewController:Login animated:YES];
    }else if ([[user objectForKey:@"userStatus"] isEqualToString:@"W"]){
        [[self rdv_tabBarController] setSelectedIndex:4];//my
        
    }
    
    _scanResultStr=@"";
    [[self rdv_tabBarController] setTabBarHidden:YES];
    self.navigationController.navigationBarHidden=YES;
    
    Token = [user objectForKey:@"tokenId"];
    
    _tishiLabel.textAlignment=NSTextAlignmentCenter;
    NSMutableAttributedString *AttributedStr1 = [[NSMutableAttributedString alloc]initWithString:@"对准条码或二维码，即可自动扫描"];
    [AttributedStr1 addAttribute:NSForegroundColorAttributeName
     
                           value:[UIColor colorWithRed:109/255.0 green:168/255.0 blue:33/255.0 alpha:1.0]
     
                           range:NSMakeRange(2, 2)];
    [AttributedStr1 addAttribute:NSForegroundColorAttributeName
     
                           value:[UIColor colorWithRed:109/255.0 green:168/255.0 blue:33/255.0 alpha:1.0]
     
                           range:NSMakeRange(5, 3)];
    _tishiLabel.attributedText = AttributedStr1;
    
    _countParentView.layer.borderColor=[UIColor colorWithRed:153/255.0f green:153/255.0f blue:153/255.0f alpha:1.0].CGColor;
    [_countParentView.layer setCornerRadius:1.5];
    [_countParentView.layer setBorderWidth:0.5];
    [_countParentView.layer setMasksToBounds:YES];

    
    
    _cornerCountLabel.layer.cornerRadius=10;
    _cornerCountLabel.layer.masksToBounds=YES;
    
    _countParentView.hidden=YES;
    _countLabel.text=@"1";
    _productNameLabel.text=@"";
    _specNameLabel1.text=@"";
    _specNameLabel.text=@"";
    titleStr=[Global getScanTitle];
    if (titleStr.length>0) {
        _titleLabel.text=titleStr;
    }
    else
    {
        _titleLabel.text=@"收银";
    }
    
    
    [self setAutoLayout];
    [self setScan];
    
    
    [_searchTextField setValue:[UIColor colorWithRed:102.0/255.0 green:102.0/255.0 blue:102.0/255.0 alpha:1.0f] forKeyPath:@"_placeholderLabel.textColor"];
    _searchTextField.clearButtonMode = UITextFieldViewModeWhileEditing; //编辑时会出现个修改X
    scanTypeStr=[Global getType];
    
    if ([scanTypeStr isEqualToString:@"SCANSTOCKMANAGE"]||[scanTypeStr isEqualToString:@"SCANMEMBER"]||[scanTypeStr isEqualToString:@"SCANORDER"]||[scanTypeStr isEqualToString:@"SCANCONPON"]) {
        _submitConfirmBtn.hidden=YES;
        _totalView.hidden=YES;
        
        if ([scanTypeStr isEqualToString:@"SCANSTOCKMANAGE"]) {
            
            _searchTextField.placeholder = @"请输入条形码/商品名搜索"; //默认显示的字
            
        }else if ([scanTypeStr isEqualToString:@"SCANMEMBER"]){
            
            _searchTextField.placeholder = @"请输入会员条形码/二维码号搜索"; //默认显示的字
            
        }else if ([scanTypeStr isEqualToString:@"SCANORDER"]){
            
            _searchTextField.placeholder = @"请输入订单条形码/二维码号搜索"; //默认显示的字
        }else if ([scanTypeStr isEqualToString:@"SCANCONPON"]){
            _searchTextField.placeholder = @"请输入优惠券码/二维码号搜索"; //默认显示的字
        }
        
        
    }
    else
    {
        _searchTextField.placeholder = @"请输入条形码/商品名搜索"; //默认显示的字
        UIButton*btnDone=[[UIButton alloc]initWithFrame:CGRectMake(55, 64,200, 44)];
        [btnDone addTarget:self action:@selector(OnTapDone) forControlEvents:UIControlEventTouchUpInside];
        [_topView addSubview:btnDone];
        [_searchTextField becomeFirstResponder];
        _searchTextField.inputView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 0.1)];
        _submitConfirmBtn.hidden=NO;
        _totalView.hidden=NO;
    }
    
    if ([scanTypeStr isEqualToString:@"SCANCASHIER"]) {
        _addBtn.hidden=NO;
        [_submitConfirmBtn setTitle:@"去结算" forState:UIControlStateNormal];
        NSMutableDictionary *params=[[NSMutableDictionary alloc] init];
        [params setObject:Token forKey:@"tokenId"];
        if (self.memberDict.count>0) {
             [params setObject:[self.memberDict objectForKey:@"memberId"] forKey:@"memberId"];
        }
       
        [HttpRequest requestData:@"Business/ShopCart/Detail" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
            if (isSuccess) {
                NSLog(@"******===%@",severDataDict.dataDict);
                if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                    [Global hideProgressHUDInternal:self.view];
                    if ([[NSString stringWithFormat:@"%@",[severDataDict.dataDict objectForKey:@"totalQty"]]intValue]==0) {
                        _cornerCountLabel.hidden=YES;
                    }else{
                     _cornerCountLabel.text=[NSString stringWithFormat:@"%@",[severDataDict.dataDict objectForKey:@"totalQty"]];
                         _cornerCountLabel.hidden=NO;
                    }
                   
                    _totalLabel.text=[NSString stringWithFormat:@"%.2f",[[severDataDict.dataDict objectForKey:@"ySelMoney"]doubleValue]];

                }
                else
                {
                    [Global hideProgressHUDInternal:self.view];
                    NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                    //  [Global showTextHud:requestResultStr view:self.view];
                    [Global showTextHudSub:requestResultStr view:self.view];
                    
                }
                
            }else
            {
                [Global hideProgressHUDInternal:self.view];
                [Global showTextHudSub:severDataDict.resultStr view:self.view];
            }
        }];

        
        
    }
    else
    {
        _addBtn.hidden=YES;
        [_submitConfirmBtn setTitle:@"提交" forState:UIControlStateNormal];
        
        [self getTotalCountFromDB];
        CGFloat noSpectTotalMoney=[self getTotalMoneyFromNoSpecDB];
        CGFloat hasSpectTotalMoney=[self getTotalMoneyFromHasSpecDB];
        
        _totalLabel.text=[Global floatConvertPercentile:noSpectTotalMoney+hasSpectTotalMoney];
    }
    
    
   
    
}
-(void)OnTapDone
{
    
    [_searchTextField resignFirstResponder];
    [_searchTextField becomeFirstResponder];
    _searchTextField.inputView=nil;
}
- (IBAction)topQuickPlaceOrder:(id)sender {
    [self stopReading];
    [_timer invalidate];
    _timer=nil;
    [_searchTextField resignFirstResponder];
    _searchTextField.text =@"";
    if ([scanTypeStr isEqualToString:@"SCANORDER"]) {
        OrderListViewController *stockVC = [[OrderListViewController alloc]init];
        stockVC.chooseState=@"选择";
        [self.navigationController pushViewController:stockVC animated:YES];
        
    }
    else if ([scanTypeStr isEqualToString:@"SCANMEMBER"])
    {
        MemberListViewController *stockVC = [[MemberListViewController alloc]init];
        [self.navigationController pushViewController:stockVC animated:YES];
        
    }
    else if ([scanTypeStr isEqualToString:@"SCANSTOCKMANAGE"])
    {
        StockManagementViewController *stockVC = [[StockManagementViewController alloc]init];
        stockVC.searchKeyWordStr=@"";
        [self.navigationController pushViewController:stockVC animated:YES];
    }else if ([scanTypeStr isEqualToString:@"SCANCONPON"])
    {
        MCouponBViewController *stockVC = [[MCouponBViewController alloc]init];
        stockVC.dataDict=scanConponResultArray;
        stockVC.snList=snList;
        stockVC.titleName=@"扫描记录";
        stockVC.mDelegate=self;
        [self.navigationController pushViewController:stockVC animated:YES];
    }
    else
    {
        if ([scanTypeStr isEqualToString:@"Continue"]) {
            PlaceOrderViewController *detailViewController = [[PlaceOrderViewController alloc] init];
            [Global setType:@"Continue"];
            [Global setPlaceOrderPType:@"saleItem"];
            detailViewController.ckvId=self.ckvId;
            detailViewController.ckvNo=self.ckvNo;
            detailViewController.whsName=self.whsName;
            detailViewController.itemTypeName=self.itemTypeName;
            detailViewController.whsId=self.whsId;
            detailViewController.itemTypeCode=self.itemTypeCode;
            [self.navigationController pushViewController:detailViewController animated:YES];
        }else{
        PlaceOrderViewController *placeOrderVC=[[PlaceOrderViewController alloc] init];
        placeOrderVC.memberDict=self.memberDict;
        [Global setPlaceOrderPType:@"saleItem"];
        [Global setType:scanTypeStr];
        [self.navigationController pushViewController:placeOrderVC animated:YES];
        }
    }
    
    
}
- (IBAction)topAddBtnClick:(id)sender {
    
    CashierNewPopView *popView=[[CashierNewPopView alloc] init];
    popView.delegate=self;
    [popView show];
}

- (void)textFieldDidBeginEditing:(UITextField *)textField{
    
}

#pragma mark recover the location of the view
- (void)textFieldDidEndEditing:(UITextField *)textField{
    //    self.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    
    if (textField.text.length==0) {
        
        if ([scanTypeStr isEqualToString:@"SCANSTOCKMANAGE"]||[scanTypeStr isEqualToString:@"SCANMEMBER"]||[scanTypeStr isEqualToString:@"SCANORDER"]||[scanTypeStr isEqualToString:@"SCANCONPON"])
        {
            [textField resignFirstResponder];
        }else{
            [_searchTextField resignFirstResponder];
            _searchTextField.inputView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 0.1)];
            [_searchTextField becomeFirstResponder];
            
        }
    }else{
        
        if ([scanTypeStr isEqualToString:@"SCANSTOCKMANAGE"])
        {
            [self stopReading];
            [_timer invalidate];
            _timer=nil;
            StockManagementViewController *stockVC = [[StockManagementViewController alloc]init];
            stockVC.searchKeyWordStr=textField.text;
            [self.navigationController pushViewController:stockVC animated:YES];
            textField.text=@"";
            [textField resignFirstResponder];
            
        }else if([scanTypeStr isEqualToString:@"SCANCONPON"]) {
            [self stopReading];
            [_timer invalidate];
            _timer=nil;
            [self requestConponDetail:textField.text];
            textField.text=@"";
            [textField resignFirstResponder];
            
        }else if([scanTypeStr isEqualToString:@"SCANMEMBER"]) {
            [self stopReading];
            [_timer invalidate];
            _timer=nil;
            MembershipDetailsViewController *stockVC = [[MembershipDetailsViewController alloc]init];
            stockVC.memberId=textField.text;
            [self.navigationController pushViewController:stockVC animated:YES];
            textField.text=@"";
            [textField resignFirstResponder];
        }else if([scanTypeStr isEqualToString:@"SCANORDER"]) {
            [self stopReading];
            [_timer invalidate];
            _timer=nil;
            OrderDetailViewController *stockVC = [[OrderDetailViewController alloc]init];
            stockVC.orderId=textField.text;
            stockVC.sat=@"cashier";
            [self.navigationController pushViewController:stockVC animated:YES];
            textField.text=@"";
            [textField resignFirstResponder];
            
        }else{
            
            
            [Global showIndeterminateHud:@"加载中，请稍后。。。" delay:30 view:self.view];
            NSMutableDictionary *params=[[NSMutableDictionary alloc] init];
            [params setObject:Token forKey:@"tokenId"];
            [params setObject:@"1" forKey:@"PageIndex"];
            [params setObject:@"20" forKey:@"PageSize"];
            
            [params setObject:textField.text forKey:@"sword"];
            [HttpRequest requestData:@"Product/Search" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
                
                if (isSuccess) {
                    NSLog(@"******===%@",severDataDict.dataDict);
                    if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                        [Global hideProgressHUDInternal:self.view];
                        if ([[severDataDict.dataDict objectForKey:@"TotalCount"] integerValue]==1) {
                            
                            for (NSDictionary* dicc in [severDataDict.dataDict objectForKey:@"DataLine"] )
                            {
                                NSMutableArray*itemIdAarry=[[NSMutableArray alloc]init];
                                [itemIdAarry addObject:[dicc valueForKey:@"itemId"]];
                                stringValue=itemIdAarry[0];
                                [_captureSession stopRunning];
                                _captureSession = nil;
                                [_timer invalidate];
                                _timer=nil;
                                [self play];
                                [self requestItemDetail:itemIdAarry[0]];
                            }
                        }else{
                            
                            
                            [self stopReading];
                            [_timer invalidate];
                            _timer=nil;
                            [_searchTextField resignFirstResponder];
                            CashierNewSearchViewController *searchVC=[[CashierNewSearchViewController alloc] init];
                            searchVC.delegate=self;
                            searchVC.keyWordStr=textField.text;
                            [Global setPlaceOrderPType:@"saleItem"];
                            [Global setType:scanTypeStr];
                            [self.navigationController pushViewController:searchVC animated:YES];
                           
                        }
                        textField.text=@"";
                    }
                    else
                    {
                        [Global hideProgressHUDInternal:self.view];
                        NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                        //  [Global showTextHud:requestResultStr view:self.view];
                        [Global showTextHudSub:requestResultStr view:self.view];
                        
                    }
                    
                }else
                {
                    [Global hideProgressHUDInternal:self.view];
                    [Global showTextHudSub:severDataDict.resultStr view:self.view];
                }
            }];
            
        }
    }
    
    return YES;
}
#pragma mark CashierNewSearchDelegate
-(void)CashierNewSearchCellCliCK:(CashierNewSearchDataModel *)model
{

     specIdStr=model.specId;
    [self performSelector:@selector(request) withObject:nil afterDelay:1];

    
}
-(void)request{

    [_captureSession stopRunning];
    _captureSession = nil;
    [_timer invalidate];
    _timer=nil;
    [self play];
   
    [self requestItemDetail:specIdStr];
}
#pragma mark CashierNewPopViewDelegate
-(void)quickCashButtonClick
{
    [self stopReading];
    [_timer invalidate];
    _timer=nil;
    RapidCashierViewController*de = [[RapidCashierViewController alloc] init];
    de.memberDict=self.memberDict;
    [self.navigationController pushViewController:de animated:YES];
    
}
-(void)unPayedOrderButtonClick
{
    [self stopReading];
    [_timer invalidate];
    _timer=nil;
    OrderListViewController*de = [[OrderListViewController alloc] init];
    de.chooseState=@"";
    de.filterNPay=@"1";
    de.chooseState=@"选择";
    [self.navigationController pushViewController:de animated:YES];
    
}
-(void)historyOrderButtonClick
{
    
    [self stopReading];
    [_timer invalidate];
    _timer=nil;
    GatheringListViewController*de = [[GatheringListViewController alloc] init];
    [self.navigationController pushViewController:de animated:YES];
    
}
-(fmDataModel *)getDataFromFM
{
    NSArray *resultArray= [NoSpecFmdbTool queryLeftJoin:scanTypeStr userToken:Token];
    fmDataModel *fmModel=[fmDataModel dataModelWithArray:[resultArray mutableCopy]];
    return fmModel;
}
- (IBAction)confirmSubmit:(id)sender {
    
if (_cornerCountLabel.text.intValue>0) {
        if ([scanTypeStr isEqualToString:@"SCANCASHIER"]) {
            [Global showIndeterminateHud:@"加载中，请稍后。。。" delay:30 view:self.view];
            NSMutableDictionary *params=[[NSMutableDictionary alloc] init];
            [params setObject:Token forKey:@"tokenId"];
            [HttpRequest requestData:@"Business/ShopCart/Confirm" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
                if (isSuccess) {
                    if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                        [Global hideProgressHUDInternal:self.view];
                        _scanResultStr=@"";
                        [self stopReading];
                        [_timer invalidate];
                        _timer=nil;
                        OrderExtAddViewController *shouyinVC=[[OrderExtAddViewController alloc] init];//2.0{9个参数 少2个}
                        shouyinVC.saveTypeStr=scanTypeStr;
                        shouyinVC.dataDictionary=  severDataDict.dataDict;
                        shouyinVC .orderType=@"order";
                        shouyinVC.memberDict=self.memberDict;
                        [self.navigationController pushViewController:shouyinVC animated:YES];
                        
                    }
                    else
                    {
                        [Global hideProgressHUDInternal:self.view];
                        NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                        [Global showTextHudSub:requestResultStr view:self.view];
                        
                    }
                    
                }else
                {
                    [Global hideProgressHUDInternal:self.view];
                    [Global showTextHudSub:severDataDict.resultStr view:self.view];
                }
            }];

            
           
        }else{
            _scanResultStr=@"";
            [self stopReading];
            [_timer invalidate];
            _timer=nil;
            
            fmDataModel *model=  [self getDataFromFM];
            
                if ([scanTypeStr isEqualToString:@"SCANCASHIER"]) {
                OrderExtAddViewController *shouyinVC=[[OrderExtAddViewController alloc] init];//2.0{9个参数 少2个}
                shouyinVC.headImageFullArray=model.productImageArray;
                shouyinVC.itemCodeArray=model.productItemCodeArray;
                shouyinVC.specNameArray=model.productSpecNameArray;
                shouyinVC.itemIdArray= model.productIDArray;
                shouyinVC.itemNameArray=model.productNameArray;
                shouyinVC.specIdArray=model.productSpecIDArray;
                shouyinVC.dealPriceArray=model.productPriceArray;
                shouyinVC.quantityArray=model.productCountArray;
                shouyinVC.saveTypeStr=scanTypeStr;
                shouyinVC .orderType=@"order";
                shouyinVC.memberDict=self.memberDict;
                [self.navigationController pushViewController:shouyinVC animated:YES];
            }else{
                
                
                [self next];//入库 出库 要货 调拨
            }
            
        }


    }else{
        UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:@"提示" message:@"您未选择商品" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alertView show];
    }

}
-(void)next
{
    fmDataModel *model=  [self getDataFromFM];
    if (model.productItemCodeArray.count>0) {
        _scanResultStr=@"";
        [self stopReading];
        [_timer invalidate];
        _timer=nil;
        
        if ([scanTypeStr isEqualToString:@"Continue"]) {
            BusinessCheckVouchContinueViewController *detailViewController = [[BusinessCheckVouchContinueViewController alloc] init];
            detailViewController.titleName=@"继续盘点";
            detailViewController.Whs=@"Continue";
            detailViewController.ckvId=self.ckvId;
            detailViewController.ckvNo=self.ckvNo;
            detailViewController.whsName=self.whsName;
            detailViewController.itemTypeName=self.itemTypeName;
            detailViewController.whsId=self.whsId;
            detailViewController.itemTypeCode=self.itemTypeCode;
            detailViewController.saveTypeStr=scanTypeStr;
            
            detailViewController. itemCodeArray=model.productItemCodeArray;
            detailViewController. itemIdArray=model.productIDArray;
            detailViewController. itemNameArray=model.productNameArray;
            detailViewController. headImageFullArray=model.productImageArray;
            detailViewController. dealPriceArray=model.productPriceArray;
            detailViewController. specIdArray=model.productSpecIDArray;
            detailViewController. quantityArray=model.productCountArray;
            detailViewController. specNameArray=model.productSpecNameArray;
            [self.navigationController pushViewController:detailViewController animated:YES];
            
        }else{

        WhsInAddViewController *detailViewController = [[WhsInAddViewController alloc] init];
        detailViewController.saveTypeStr=scanTypeStr;
        detailViewController.itemCodeArray=model.productItemCodeArray;
        detailViewController.itemIdArray=model.productIDArray;
        detailViewController.itemNameArray=model.productNameArray;
        detailViewController.headImageFullArray=model.productImageArray;
        detailViewController.dealPriceArray=model.productPriceArray;
        detailViewController.specIdArray=model.productSpecIDArray;
        detailViewController.quantityArray=model.productCountArray;
        detailViewController.specNameArray=model.productSpecNameArray;
        [self.navigationController pushViewController:detailViewController animated:YES];
        }
    }
}
-(void)setScan
{
    isDown=NO;
    if (_captureSession!=nil) {
        [_captureSession stopRunning];
        [_videoPreviewLayer removeFromSuperlayer];
        _captureSession = nil;
    }
    if (_timer==nil) {
        
        _timer = [NSTimer scheduledTimerWithTimeInterval:0.02 target:self selector:@selector(lineAnimation) userInfo:nil repeats:YES];
        
        [self startRead];
    }
    [self.view bringSubviewToFront:_bgImageView
     ];
    [self.view bringSubviewToFront:_topView
     ];
    
    [self.view bringSubviewToFront:_scanBottomView
     ];
    [self.view bringSubviewToFront:_ScanLeftView
     ];
    [self.view bringSubviewToFront:_scanTopView
     ];
    [self.view bringSubviewToFront:_scanRightView
     ];
    [self.view bringSubviewToFront:_submitConfirmBtn
     ];
    [self.view bringSubviewToFront:_totalView
     ];
    [self.view bringSubviewToFront:_countParentView
     ];
    [self.view bringSubviewToFront:_tishiLabel
     ];
    [self.view bringSubviewToFront:_productNameLabel
     ];
    [self.view bringSubviewToFront:_lineFrameImage
     ];
    [self.view bringSubviewToFront:_lineLabel
     ];
    [self.view bringSubviewToFront:_specNameLabel
     ];
    [self.view bringSubviewToFront:_specNameLabel1
     ];
    [self.view bringSubviewToFront:_lineImage
     ];
    
}
-(void)lineAnimation
{
    
    if (isDown==NO) {
        num++;
        [_lineImage mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_lineFrameImage.mas_left).with.offset(20);
            make.right.equalTo(_lineFrameImage.mas_right).with.offset(-20);
            make.height.equalTo(@10);
            make.top.equalTo(_lineFrameImage.mas_top).with.offset(2*num);
        }];
        if (2*num+10>=_lineFrameImage.frame.size.height) {
            isDown=YES;
        }
    }
    else
    {
        num--;
        [_lineImage mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_lineFrameImage.mas_left).with.offset(20);
            make.right.equalTo(_lineFrameImage.mas_right).with.offset(-20);
            make.height.equalTo(@10);
            make.top.equalTo(_lineFrameImage.mas_top).with.offset(2*num);
        }];
        
        if (num==0) {
            isDown=NO;
        }
    }
    
}

-(BOOL)startRead
{
    
    NSError *error;
    
    AVCaptureDevice *captureDevice=[AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    AVCaptureDeviceInput *input=[AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error];
    if (!input) {
        return NO;
    }
    _captureSession = [[AVCaptureSession alloc] init];
    if ([_captureSession canAddInput:input]) {
        [_captureSession addInput:input];
    }
    
    AVCaptureMetadataOutput *captureMetadataOutput = [[AVCaptureMetadataOutput alloc] init];
    captureMetadataOutput.rectOfInterest=_lineFrameImage.bounds;
    if ([_captureSession canAddOutput:captureMetadataOutput]) {
        [_captureSession addOutput:captureMetadataOutput];
    }
    
       dispatch_queue_t dispatchQueue;
    dispatchQueue = dispatch_queue_create("myQueue", NULL);
    [captureMetadataOutput setMetadataObjectsDelegate:self queue:dispatchQueue];
    captureMetadataOutput.metadataObjectTypes =@[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code,AVMetadataObjectTypeCode128Code,AVMetadataObjectTypeCode93Code,AVMetadataObjectTypeEAN8Code,AVMetadataObjectTypeCode39Code];
    
    [ captureMetadataOutput setRectOfInterest : CGRectMake (( 154 )/ ScreenHeight ,(( ScreenWidth - 250 )/ 2 )/ ScreenWidth , 250 / ScreenHeight , 250 / ScreenWidth )];

//    [captureMetadataOutput setRectOfInterest:_lineFrameImage.bounds];
    _videoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:_captureSession];
    
    [_videoPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
    [_videoPreviewLayer setFrame:CGRectMake(0, 0,ScreenWidth,ScreenHeight)];
    [_videoPreviewLayer setBackgroundColor:(__bridge CGColorRef)[Global parseColor:@"#66000000"]];
    [self.view.layer addSublayer:_videoPreviewLayer];
    [_captureSession startRunning];
    return YES;
}
-(void)stopReading{
    
    [_captureSession stopRunning];
    _captureSession = nil;
    [_videoPreviewLayer removeFromSuperlayer];
}

- (void)play
{
    
    sound = kSystemSoundID_Vibrate;//震动
    //    NSString *path = [NSString stringWithFormat:@"/System/Library/Audio/UISounds/%@.%@",@"jbl_confirm",@"caf"];
    //    OSStatus error = AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:path],&sound);
    AudioServicesPlaySystemSound(sound);
}

-(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
    
    if (metadataObjects != nil && [metadataObjects count] > 0) {
        AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex:0];
        stringValue = metadataObject.stringValue;
        if ([scanTypeStr isEqualToString:@"SCANSTOCKMANAGE"]) {
            if (![stringValue isEqualToString:_scanResultStr]) {
                
                //                  NSLog(@"sstype====%@",scanTypeStr);
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self play];
                    StockManagementViewController *stockVC = [[StockManagementViewController alloc]init];
                    stockVC.searchKeyWordStr=stringValue;
                    [self.navigationController pushViewController:stockVC animated:YES];
                });
            }
            _scanResultStr=@"";
            [self stopReading];
            [_timer invalidate];
            _timer=nil;
        }
        else if([scanTypeStr isEqualToString:@"SCANORDER"]) {
            _scanResultStr=@"";
            if (![stringValue isEqualToString:_scanResultStr])
            {
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self play];
                    OrderDetailViewController *stockVC = [[OrderDetailViewController alloc]init];
                    stockVC.orderId=stringValue;
                    stockVC.sat=@"cashier";
                    [self.navigationController pushViewController:stockVC animated:YES];
                });
            }
            
            [self stopReading];
            [_timer invalidate];
            _timer=nil;
            
        }else if([scanTypeStr isEqualToString:@"SCANCONPON"]) {
            _scanResultStr=@"";
            if (![stringValue isEqualToString:_scanResultStr])
            {
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self play];
                    
                     [self performSelectorOnMainThread:@selector(loadConponVC) withObject:nil waitUntilDone:NO];

                });
            }
            
            [_captureSession stopRunning];
            _captureSession = nil;
            [_timer invalidate];
            _timer=nil;
           
            
        }

        else if([scanTypeStr isEqualToString:@"SCANMEMBER"]) {
            _scanResultStr=@"";
            if (![stringValue isEqualToString:_scanResultStr])
            {
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self play];
                    MembershipDetailsViewController *stockVC = [[MembershipDetailsViewController alloc]init];
                    stockVC.memberId=stringValue;
                    [self.navigationController pushViewController:stockVC animated:YES];
                });
            }
            
            [self stopReading];
            [_timer invalidate];
            _timer=nil;
            
            
            
        }else{
            
            [_captureSession stopRunning];
            _captureSession = nil;
            [_timer invalidate];
            _timer=nil;
            [self play];
            _submitConfirmBtn.userInteractionEnabled=NO;
            [self performSelectorOnMainThread:@selector(loadItemDetail) withObject:nil waitUntilDone:NO];
            //            [self performSelector:@selector(doneWithView) withObject:self afterDelay:1.0f];
            //             if (![stringValue isEqualToString:_scanResultStr]) {
            //                  dispatch_async(dispatch_get_main_queue(), ^{
            //                 [self performSelectorOnMainThread:@selector(reChangeCount) withObject:nil waitUntilDone:NO];
            //                 [self reChangeCount];
            //                _searchTextField.text=stringValue;
            //                [self requestItemDetail:stringValue];
            //                _scanResultStr=stringValue;
            //                  });
            //
            //             }
        }
        
    }
}
-(void)loadConponVC
{
    _searchTextField.text=stringValue;
    [self requestConponDetail:stringValue];
    
}
-(void)requestConponDetail:(NSString *)codeStr
{
    if (codeStr.length>15) {
        NSString *originalString =codeStr;
        NSRange range = [originalString rangeOfString:@"code/"]; //现获取要截取的字符串位置
        NSString * result = [originalString substringFromIndex:range.location];
        result1 = [result substringFromIndex:5];
    }else{
    
        result1 =codeStr;

    }
    _searchTextField.text=@"";
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    Token = [user objectForKey:@"tokenId"];
     NSLog(@"CashierNewViewcontrollerToken-------%@",result1);
    NSMutableDictionary *params = [NSMutableDictionary new];
    [params setValue:Token forKey:@"tokenId"];
   [params setValue:result1 forKey:@"sn"];
    [Global showIndeterminateHud:@"加载中，请稍后。。。" delay:30 view:self.view];
    [HttpRequest requestData:@"Business/Coupon/Check" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
        if (isSuccess) {
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                
//                NSLog(@"-------%@",severDataDict.dataDict);
                _scanResultStr=stringValue;
                [_searchTextField resignFirstResponder];
                if ([scanConponResultArray containsObject:[severDataDict.dataDict objectForKey:@"coupon"]]) {
                
                MCouponBViewController *stockVC = [[MCouponBViewController alloc]init];
                stockVC.dataDict=scanConponResultArray;
                stockVC.snList=snList;
                stockVC.titleName=@"扫描记录";
                stockVC.mDelegate=self;
                [self.navigationController pushViewController:stockVC animated:YES];
                _searchTextField.inputView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 0.1)];
                [_searchTextField becomeFirstResponder];
              }else{
               
                  [snList addObject:result1];

                  [scanConponResultArray addObject:[severDataDict.dataDict objectForKey:@"coupon"]];
                  MCouponBViewController *stockVC = [[MCouponBViewController alloc]init];
                  stockVC.snList=snList;
                  stockVC.dataDict=scanConponResultArray;
                  stockVC.titleName=@"扫描记录";
                  stockVC.mDelegate=self;
                  [self.navigationController pushViewController:stockVC animated:YES];

              }
            }else{
                _scanResultStr=stringValue;
                [self performSelector:@selector(load) withObject:nil afterDelay:1];
                NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                [Global showTextHudSub:requestResultStr view:self.view];
            }
            }else{
            _scanResultStr=stringValue;
            [self performSelector:@selector(load) withObject:nil afterDelay:1];
            [Global showTextHudSub:severDataDict.resultStr view:self.view];
        }
    }];
     
    
}

-(void)loadItemDetail
{
    _searchTextField.text=stringValue;
    [self requestItemDetail:stringValue];
   
}
-(void)load{

    [self setScan];
    _submitConfirmBtn.userInteractionEnabled=YES;
}
-(void)reChangeCount
{
    _countLabel.text=@"1";
}
-(void)getTotalCountFromDB
{
    
    NoSpecFmdbModel *model=[NoSpecFmdbModel modalWith:Token itemId:@"" itemCode:@"" imageUrlFull:@"" itemName:@"" maxPrice:@"" minPrice:@"" salePrice:@"" invQty:@"" specType:@"" specCount:@"" typeString:scanTypeStr];
    NSString *resultStr=[NoSpecFmdbTool getCornerCount:model];
    _cornerCountLabel.text=[NSString stringWithFormat:@"%d",resultStr.intValue];
    
}
-(CGFloat)getTotalMoneyFromNoSpecDB
{
    CGFloat totalNoSpecMoney=0;
    //    PlaceOrderSubDataModel *model=modelArray[tag];
    NoSpecFmdbModel *model=[NoSpecFmdbModel modalWith:Token itemId:@"" itemCode:@"" imageUrlFull:@"" itemName:@"" maxPrice:@"" minPrice:@"" salePrice:@"" invQty:@"" specType:@"" specCount:@"" typeString:scanTypeStr];
    NSString *resultStr=[NoSpecFmdbTool getTotalNoSpecMoney:model];
    totalNoSpecMoney=resultStr.floatValue;
    return totalNoSpecMoney;
    
}
-(CGFloat)getTotalMoneyFromHasSpecDB
{
    CGFloat totalHasSpecMoney=0;
    HasSpecFmdbModel *model=[HasSpecFmdbModel modalWith:Token itemId:@"" itemCode:@"" colorSpecID:@"" sizeSpecID:@"" specName:@"" specPrice:@"" specStock:@"" specCount:@"" typeString:scanTypeStr specID:@""];
    NSString *resultStr=[HasSpecFmdbTool getTotalSpecMoney:model];
    totalHasSpecMoney=[resultStr floatValue];
    return totalHasSpecMoney;
    
}

-(void)ShopCartMerge:(NSString *)pidStr :(NSString *)specId{
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    Token = [user objectForKey:@"tokenId"];
    NSMutableDictionary *params = [NSMutableDictionary new];
    [params setValue:Token forKey:@"tokenId"];
    [params setValue:pidStr forKey:@"itemId"];
    [params setValue:specId forKey:@"specId"];
    [params setValue:_ySelQty forKey:@"quantity"];
    NSLog(@"SCANrequestItemDetail====%@",params);
    [HttpRequest requestData:@"Business/ShopCart/Merge" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
        if (isSuccess) {
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
            NSLog(@"SCANrequestItemDetail====%@",severDataDict.dataDict);
                _countParentView.hidden=NO;
                _cornerCountLabel.hidden=NO;
                _countLabel.text=[NSString stringWithFormat:@"%@",[severDataDict.dataDict objectForKey:@"cItemQty"]];
                _cornerCountLabel.text=[NSString stringWithFormat:@"%@",[severDataDict.dataDict objectForKey:@"totalQty"]];
                _totalLabel.text=[NSString stringWithFormat:@"%.2f",[[severDataDict.dataDict objectForKey:@"ySelMoney"]doubleValue]];
                
                
            if (_countLabel.text.intValue==0) {
                    _scanResultStr=@"";
                   _countParentView.hidden=YES;
                    _productNameLabel.text=@"";
//                  _cornerCountLabel.hidden=YES;
                _specNameLabel1.text=@"";
                _specNameLabel.text=@"";
                }
            [_searchTextField resignFirstResponder];
            _searchTextField.inputView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 0.1)];
            [_searchTextField becomeFirstResponder];
           
                if ( [_noCashier isEqualToString:@""]) {
                     [self performSelector:@selector(load) withObject:nil afterDelay:1];
                }else{
                
                }
                
               
               
            }else
                {
                    
                    [self performSelector:@selector(load) withObject:nil afterDelay:1];
                    NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                    [Global showTextHudSub:requestResultStr view:self.view];
                    
                }
            }
            else
            {
              
                [self performSelector:@selector(load) withObject:nil afterDelay:1];
                [Global showTextHudSub:severDataDict.resultStr view:self.view];
            }
        }];


}
-(void)requestItemDetail:(NSString *)codeStr
{
    _searchTextField.text=@"";
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    Token = [user objectForKey:@"tokenId"];
    NSMutableDictionary *params = [NSMutableDictionary new];
    [params setValue:Token forKey:@"tokenId"];
    [params setValue:codeStr forKey:@"pid"];
    [params setValue:@"Y" forKey:@"isShopCart"];
    NSLog(@"SCANrequestItemDetail====%@",params);

    [Global showIndeterminateHud:@"加载中，请稍后。。。" delay:30 view:self.view];
    [HttpRequest requestData:@"Product/Detail" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
        if (isSuccess) {
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                NSLog(@"====%@",severDataDict.dataDict);
                
                if ([scanTypeStr isEqualToString:@"SCANCASHIER"]) {
                    _noCashier=@"";
                    cashierModel=[CashierNewDataModel dataModelWithDict:severDataDict.dataDict];
                    if ([cashierModel.specType intValue]>0 )
                    {
                        _productNameLabel.text=cashierModel.itemName;
                        _specNameLabel1.text=@"规格 ";
                        _specNameLabel1.backgroundColor=[UIColor whiteColor];
                       _specNameLabel.text = [cashierModel.specName stringByReplacingOccurrencesOfString:cashierModel.itemName withString:@""];
                        [_specNameLabel1.layer setCornerRadius:1];
                        [_specNameLabel1.layer setBorderWidth:0.5];
                        [_specNameLabel1.layer setMasksToBounds:YES];
                        _specNameLabel1.layer.borderColor=[[UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:1] CGColor];
                    
                    }else{
                        _specNameLabel1.text=@"";
                        _specNameLabel.text=@"";
                        _productNameLabel.text=cashierModel.itemName;
                    }
                
                 
                    _invQty=[severDataDict.dataDict objectForKey:@"invQty"];
                    if ([[severDataDict.dataDict objectForKey:@"shopCartQty"]intValue ]>=[[severDataDict.dataDict objectForKey:@"invQty"]intValue ]) {
                        _theCurrentSpecId=[[severDataDict.dataDict objectForKey:@"currentSpec"]objectForKey:@"specId"];
                        _theCurrentItemId=[[severDataDict.dataDict objectForKey:@"currentSpec"]objectForKey:@"itemId"];
                        _ySelQty=[NSString stringWithFormat:@"%d",[NSString stringWithFormat:@"%@",[severDataDict.dataDict objectForKey:@"shopCartQty"]].intValue+1];
                        [self ShopCartMerge:[[severDataDict.dataDict objectForKey:@"currentSpec"]objectForKey:@"itemId"]:[[severDataDict.dataDict objectForKey:@"currentSpec"]objectForKey:@"specId"]];
                          [self showAlertMessage:@"已超出商品库存量"];

                    }else{
                        
                        _theCurrentSpecId=[[severDataDict.dataDict objectForKey:@"currentSpec"]objectForKey:@"specId"];
                        _theCurrentItemId=[[severDataDict.dataDict objectForKey:@"currentSpec"]objectForKey:@"itemId"];
                     _ySelQty=[NSString stringWithFormat:@"%d",[NSString stringWithFormat:@"%@",[severDataDict.dataDict objectForKey:@"shopCartQty"]].intValue+1];
                   [self ShopCartMerge:[[severDataDict.dataDict objectForKey:@"currentSpec"]objectForKey:@"itemId"]:[[severDataDict.dataDict objectForKey:@"currentSpec"]objectForKey:@"specId"]];
                    }
                
                }else{
                cashierModel=[CashierNewDataModel dataModelWithDict:severDataDict.dataDict];
                BOOL noSpecBool;
                NoSpecFmdbModel *fmModel;
                if ([cashierModel.specType intValue]>0 )
                {
                    
                    if ([cashierModel.specType intValue]>0 )
                    {
                        _productNameLabel.text=cashierModel.itemName;
                        _specNameLabel1.text=@"规格 ";
                        _specNameLabel1.backgroundColor=[UIColor whiteColor];
                        _specNameLabel.text = [cashierModel.specName stringByReplacingOccurrencesOfString:cashierModel.itemName withString:@""];
                        [_specNameLabel1.layer setCornerRadius:1];
                        [_specNameLabel1.layer setBorderWidth:0.5];
                        [_specNameLabel1.layer setMasksToBounds:YES];
                        _specNameLabel1.layer.borderColor=[[UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:1] CGColor];
                    }else{
                        _specNameLabel1.text=@"";
                        _specNameLabel.text=@"";
                        _productNameLabel.text=cashierModel.itemName;
                    }

//                    _productNameLabel.text=cashierModel.specName;
                    
                    HasSpecFmdbModel *model=[HasSpecFmdbModel modalWith:Token itemId:cashierModel.itemId itemCode:cashierModel.itemCode colorSpecID:cashierModel.colourId sizeSpecID:cashierModel.sizeId specName:cashierModel.specName specPrice:cashierModel.specPrice specStock:cashierModel.specInv specCount:@"1" typeString:scanTypeStr specID:cashierModel.specId];
                    
                    BOOL hasSpecBool;
                    if ([scanTypeStr isEqualToString:@"Allot"]||[scanTypeStr isEqualToString:@"WhsIn"]||[scanTypeStr isEqualToString:@"CheckVouch"]||[scanTypeStr isEqualToString:@"NeedOrder"]||[scanTypeStr isEqualToString:@"Continue"]||[scanTypeStr isEqualToString:@"Refund"]) {
                        hasSpecBool = [HasSpecFmdbTool modifySpecCountNoLimit:model countText:@"1" ];
                    }
                    else
                    {
                        hasSpecBool= [HasSpecFmdbTool modifySpecCountWithLimit:model countText:@"1"];
                    }
                    if (hasSpecBool) {
                        //                    NSLog(@"rrrrrrrr000000cashierModel.specInv====%@",cashierModel.specInv);
                        fmModel=[NoSpecFmdbModel modalWith:Token itemId:cashierModel.itemId itemCode:cashierModel.itemCode imageUrlFull:cashierModel.imageUrlFull itemName:cashierModel.itemName maxPrice:cashierModel.maxPrice minPrice:cashierModel.minPrice salePrice:cashierModel.salePrice invQty:cashierModel.specInv specType:cashierModel.specType specCount:@"1" typeString:scanTypeStr];
                        if ([scanTypeStr isEqualToString:@"Allot"]||[scanTypeStr isEqualToString:@"WhsIn"]||[scanTypeStr isEqualToString:@"CheckVouch"]||[scanTypeStr isEqualToString:@"NeedOrder"]||[scanTypeStr isEqualToString:@"Continue"]||[scanTypeStr isEqualToString:@"Refund"]) {
                            noSpecBool=  [NoSpecFmdbTool modifyNoSpecCountNoLimit:fmModel countText:@"1"];
                        }
                        else
                            noSpecBool=  [NoSpecFmdbTool modifyNoSpecCountWithLimit:fmModel countText:@"1"];
                    }
                }
                
                else
                {
                    //                    NSLog(@"rrrrrrrr1");
                    _productNameLabel.text=cashierModel.itemName;
                    fmModel=[NoSpecFmdbModel modalWith:Token itemId:cashierModel.itemId itemCode:cashierModel.itemCode imageUrlFull:cashierModel.imageUrlFull itemName:cashierModel.itemName maxPrice:cashierModel.maxPrice minPrice:cashierModel.minPrice salePrice:cashierModel.salePrice invQty:cashierModel.invQty specType:cashierModel.specType specCount:@"1" typeString:scanTypeStr];
                    if ([scanTypeStr isEqualToString:@"Allot"]||[scanTypeStr isEqualToString:@"WhsIn"]||[scanTypeStr isEqualToString:@"CheckVouch"]||[scanTypeStr isEqualToString:@"NeedOrder"]||[scanTypeStr isEqualToString:@"Continue"]||[scanTypeStr isEqualToString:@"Refund"]) {
                        noSpecBool=  [NoSpecFmdbTool modifyNoSpecCountNoLimit:fmModel countText:@"1"];
                    }
                    else
                        noSpecBool=  [NoSpecFmdbTool modifyNoSpecCountWithLimit:fmModel countText:@"1"];
                }
                
                _countParentView.hidden=NO;
                if (noSpecBool) {
                    
                    CGFloat noSpectTotalMoney=[self getTotalMoneyFromNoSpecDB];
                    CGFloat hasSpectTotalMoney=[self getTotalMoneyFromHasSpecDB];
                    _totalLabel.text=[Global floatConvertPercentile:noSpectTotalMoney+hasSpectTotalMoney];
                    [self getTotalCountFromDB];
                    //                  [self getTotalMoneyFromNoSpecDB];
                    
                    if (![stringValue isEqualToString:_scanResultStr]) {
                        
                        _countLabel.text=@"1";
                        _scanResultStr=stringValue;
                    }else{
                        
                        _countLabel.text=[NSString stringWithFormat:@"%d",_countLabel.text.intValue+1];
                        _scanResultStr=stringValue;
                    }
               
                
                }else{
                    _countLabel.text=@"0";
                }
                
                if (specIdStr.length>1) {
                    specIdStr=@"";
                     [self performSelector:@selector(load) withObject:nil afterDelay:1];
                }else{
                    [self performSelector:@selector(load) withObject:nil afterDelay:1];
                }
                
                [_searchTextField resignFirstResponder];
                _searchTextField.inputView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 0.1)];
                [_searchTextField becomeFirstResponder];
               
            }
            }
            else
            {
                _scanResultStr=stringValue;
                [self performSelector:@selector(load) withObject:nil afterDelay:1];
                _countParentView.hidden=YES;
                _productNameLabel.text=[severDataDict.dataDict objectForKey:@"ResultString"];
                NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                [Global showTextHudSub:requestResultStr view:self.view];
                
            }
        }
        else
        {
            _scanResultStr=stringValue;
            [self performSelector:@selector(load) withObject:nil afterDelay:1];
            [Global showTextHudSub:severDataDict.resultStr view:self.view];
        }
    }];
    
}

-(IBAction)selectedGoodsBtnClick:(id)sender
{
    [self stopReading];
    [_timer invalidate];
    _timer=nil;
    _scanResultStr=@"";
    
    if ([scanTypeStr isEqualToString:@"Continue"]) {
        SelectedGoodNewViewController *selectedGoodVC=[[SelectedGoodNewViewController alloc] init];//2.0{9个参数 少2个}
        selectedGoodVC.typeString=scanTypeStr;
        //下面继续盘点的带出来的数据
        selectedGoodVC.ckvId=self.ckvId;
        selectedGoodVC.ckvNo=self.ckvNo;
        selectedGoodVC.whsName=self.whsName;
        selectedGoodVC.itemTypeName=self.itemTypeName;
        selectedGoodVC.whsId=self.whsId;
        selectedGoodVC.itemTypeCode=self.itemTypeCode;
        [self.navigationController pushViewController:selectedGoodVC animated:YES];

    
    }else{
        if ([scanTypeStr isEqualToString:@"SCANCASHIER"]) {

        SelectedGoodNewViewController1 *selectedGoodVC=[[SelectedGoodNewViewController1 alloc] init];//2.0{9个参数 少2个}
        selectedGoodVC.memberDict=self.memberDict;
        selectedGoodVC.typeString=scanTypeStr;
        [self.navigationController pushViewController:selectedGoodVC animated:YES];
        }else{
        
            SelectedGoodNewViewController *selectedGoodVC=[[SelectedGoodNewViewController alloc] init];//2.0{9个参数 少2个}
            selectedGoodVC.memberDict=self.memberDict;
            selectedGoodVC.typeString=scanTypeStr;
            [self.navigationController pushViewController:selectedGoodVC animated:YES];
        }

    }
}

- (IBAction)subtractCountBtnClick:(id)sender {
    
    if ([_countLabel.text intValue]>=1) {
        
        if ([scanTypeStr isEqualToString:@"SCANCASHIER"]) {
                    _noCashier=@"noCashier";
            _ySelQty=[NSString stringWithFormat:@"%d",_ySelQty.intValue-1];
            [self ShopCartMerge:_theCurrentItemId:_theCurrentSpecId];
            
            
        }else{
            if ([cashierModel.specType intValue]==0) {
            NoSpecFmdbModel *fmModel=[NoSpecFmdbModel modalWith:Token itemId:cashierModel.itemId itemCode:cashierModel.itemCode imageUrlFull:cashierModel.imageUrlFull itemName:cashierModel.itemName maxPrice:cashierModel.maxPrice minPrice:cashierModel.minPrice salePrice:cashierModel.salePrice invQty:cashierModel.invQty specType:cashierModel.specType specCount:@"" typeString:scanTypeStr];
            BOOL noSpecBool;
            
            if ([scanTypeStr isEqualToString:@"Allot"]||[scanTypeStr isEqualToString:@"WhsIn"]||[scanTypeStr isEqualToString:@"CheckVouch"]||[scanTypeStr isEqualToString:@"NeedOrder"]||[scanTypeStr isEqualToString:@"Continue"]||[scanTypeStr isEqualToString:@"Refund"])
                noSpecBool=  [NoSpecFmdbTool modifyNoSpecCountNoLimit:fmModel countText:@"-1"];
            else
                noSpecBool=  [NoSpecFmdbTool modifyNoSpecCountWithLimit:fmModel countText:@"-1"];
            if (noSpecBool) {
                
                _countLabel.text=[NSString stringWithFormat:@"%d",_countLabel.text.intValue-1];
                [self getTotalCountFromDB];
                CGFloat noSpectTotalMoney=[self getTotalMoneyFromNoSpecDB];
                CGFloat hasSpectTotalMoney=[self getTotalMoneyFromHasSpecDB];
                _totalLabel.text=[Global floatConvertPercentile:noSpectTotalMoney+hasSpectTotalMoney];
                if (_countLabel.text.intValue==0) {
                    _scanResultStr=@"";
                    _countParentView.hidden=YES;
                    _productNameLabel.text=@"";
                }
                
            }
            
            
        }
        else
        {
            HasSpecFmdbModel *model=[HasSpecFmdbModel modalWith:Token itemId:cashierModel.itemId itemCode:cashierModel.itemCode colorSpecID:cashierModel.colourId sizeSpecID:cashierModel.sizeId specName:cashierModel.specName specPrice:cashierModel.specPrice specStock:cashierModel.specInv specCount:@"" typeString:scanTypeStr specID:@""];
            BOOL hasSpecBool;
            if ([scanTypeStr isEqualToString:@"Allot"]||[scanTypeStr isEqualToString:@"WhsIn"]||[scanTypeStr isEqualToString:@"CheckVouch"]||[scanTypeStr isEqualToString:@"NeedOrder"]||[scanTypeStr isEqualToString:@"Continue"]||[scanTypeStr isEqualToString:@"Refund"]) {
                hasSpecBool = [HasSpecFmdbTool modifySpecCountNoLimit:model countText:@"-1" ];
            }
            else
            {
                hasSpecBool= [HasSpecFmdbTool modifySpecCountWithLimit:model countText:@"-1"];
            }
            
            
            if (hasSpecBool) {
                NoSpecFmdbModel *fmModel=[NoSpecFmdbModel modalWith:Token itemId:cashierModel.itemId itemCode:cashierModel.itemCode imageUrlFull:cashierModel.imageUrlFull itemName:cashierModel.itemName maxPrice:cashierModel.maxPrice minPrice:cashierModel.minPrice salePrice:cashierModel.salePrice invQty:cashierModel.invQty specType:cashierModel.specType specCount:@"" typeString:scanTypeStr];
                
                if ([scanTypeStr isEqualToString:@"Allot"]||[scanTypeStr isEqualToString:@"WhsIn"]||[scanTypeStr isEqualToString:@"CheckVouch"]||[scanTypeStr isEqualToString:@"NeedOrder"]||[scanTypeStr isEqualToString:@"Continue"]||[scanTypeStr isEqualToString:@"Refund"]) {
                    [NoSpecFmdbTool modifyNoSpecCountNoLimit:fmModel countText:@"-1"];
                }
                else
                    [NoSpecFmdbTool modifyNoSpecCountWithLimit:fmModel countText:@"-1"];
                
                _countLabel.text=[NSString stringWithFormat:@"%d",_countLabel.text.intValue-1];
                if (_countLabel.text.intValue==0) {
                    _scanResultStr=@"";
                    _countParentView.hidden=YES;
                    _productNameLabel.text=@"";
                }
                
                [self getTotalCountFromDB];
                CGFloat noSpectTotalMoney=[self getTotalMoneyFromNoSpecDB];
                CGFloat hasSpectTotalMoney=[self getTotalMoneyFromHasSpecDB];
                _totalLabel.text=[Global floatConvertPercentile:noSpectTotalMoney+hasSpectTotalMoney];
                
            }
            
            
        }
        
        }
    }else{
        _scanResultStr=@"";
        _countParentView.hidden=YES;
        _productNameLabel.text=@"";
        
    
    }
}
- (IBAction)addCountBtnClick:(id)sender {
    if ([scanTypeStr isEqualToString:@"SCANCASHIER"]) {
        if ([_ySelQty intValue ]>=[_invQty intValue ]) {
           
            
            _noCashier=@"noCashier";
            _ySelQty=[NSString stringWithFormat:@"%d",_countLabel.text.intValue+1];
            [self ShopCartMerge:_theCurrentItemId:_theCurrentSpecId];
            [self showAlertMessage:@"已超出商品库存量"];
        }else{
            _noCashier=@"noCashier";
            _ySelQty=[NSString stringWithFormat:@"%d",_ySelQty.intValue+1];
            [self ShopCartMerge:_theCurrentItemId:_theCurrentSpecId];
        }

        
        
        }else{
    if ([cashierModel.specType intValue]==0) {
        NoSpecFmdbModel *fmModel=[NoSpecFmdbModel modalWith:Token itemId:cashierModel.itemId itemCode:cashierModel.itemCode imageUrlFull:cashierModel.imageUrlFull itemName:cashierModel.itemName maxPrice:cashierModel.maxPrice minPrice:cashierModel.minPrice salePrice:cashierModel.salePrice invQty:cashierModel.invQty specType:cashierModel.specType specCount:@"" typeString:scanTypeStr];
        BOOL noSpecBool;
        if ([scanTypeStr isEqualToString:@"Allot"]||[scanTypeStr isEqualToString:@"WhsIn"]||[scanTypeStr isEqualToString:@"CheckVouch"]||[scanTypeStr isEqualToString:@"NeedOrder"]||[scanTypeStr isEqualToString:@"Continue"]||[scanTypeStr isEqualToString:@"Refund"]) {
            noSpecBool=  [NoSpecFmdbTool modifyNoSpecCountNoLimit:fmModel countText:@"1"];
        }
        else
            noSpecBool=  [NoSpecFmdbTool modifyNoSpecCountWithLimit:fmModel countText:@"1"];
        
        if (noSpecBool) {
            
            _countLabel.text=[NSString stringWithFormat:@"%d",_countLabel.text.intValue+1];
            [self getTotalCountFromDB];
            CGFloat noSpectTotalMoney=[self getTotalMoneyFromNoSpecDB];
            CGFloat hasSpectTotalMoney=[self getTotalMoneyFromHasSpecDB];
            _totalLabel.text=[Global floatConvertPercentile:noSpectTotalMoney+hasSpectTotalMoney];
        }
    }
    else
    {
        
        HasSpecFmdbModel *model=[HasSpecFmdbModel modalWith:Token itemId:cashierModel.itemId itemCode:cashierModel.itemCode colorSpecID:cashierModel.colourId sizeSpecID:cashierModel.sizeId specName:cashierModel.specName specPrice:cashierModel.specPrice specStock:cashierModel.specInv specCount:@"" typeString:scanTypeStr specID:@""];
        BOOL hasSpecBool;
        if ([scanTypeStr isEqualToString:@"Allot"]||[scanTypeStr isEqualToString:@"WhsIn"]||[scanTypeStr isEqualToString:@"CheckVouch"]||[scanTypeStr isEqualToString:@"NeedOrder"]||[scanTypeStr isEqualToString:@"Continue"]||[scanTypeStr isEqualToString:@"Refund"]) {
            hasSpecBool = [HasSpecFmdbTool modifySpecCountNoLimit:model countText:@"1" ];
        }
        else
        {
            hasSpecBool= [HasSpecFmdbTool modifySpecCountWithLimit:model countText:@"1"];
        }
        
        
        if (hasSpecBool) {
            NoSpecFmdbModel *fmModel=[NoSpecFmdbModel modalWith:Token itemId:cashierModel.itemId itemCode:cashierModel.itemCode imageUrlFull:cashierModel.imageUrlFull itemName:cashierModel.itemName maxPrice:cashierModel.maxPrice minPrice:cashierModel.minPrice salePrice:cashierModel.salePrice invQty:cashierModel.invQty specType:cashierModel.specType specCount:@"" typeString:scanTypeStr];
            
            if ([scanTypeStr isEqualToString:@"Allot"]||[scanTypeStr isEqualToString:@"WhsIn"]||[scanTypeStr isEqualToString:@"CheckVouch"]||[scanTypeStr isEqualToString:@"NeedOrder"]||[scanTypeStr isEqualToString:@"Continue"]||[scanTypeStr isEqualToString:@"Refund"]) {
                [NoSpecFmdbTool modifyNoSpecCountNoLimit:fmModel countText:@"1"];
            }
            else
                [NoSpecFmdbTool modifyNoSpecCountWithLimit:fmModel countText:@"1"];
            
            
            
            _countLabel.text=[NSString stringWithFormat:@"%d",_countLabel.text.intValue+1];
            [self getTotalCountFromDB];
            CGFloat noSpectTotalMoney=[self getTotalMoneyFromNoSpecDB];
            CGFloat hasSpectTotalMoney=[self getTotalMoneyFromHasSpecDB];
            _totalLabel.text=[Global floatConvertPercentile:noSpectTotalMoney+hasSpectTotalMoney];
            
        }
    }
    //    else
    //    {
    //        UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:@"提示" message:@"已超库存量" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
    //        [alertView show];
    //    }
    
    
    }
}


-(void)setAutoLayout
{
    [_topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left) ;
        make.right.equalTo(self.view.mas_right) ;
        make.height.equalTo(@106) ;
        make.top.equalTo(self.view.mas_top);
    }];
    [_titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(_topView.mas_centerX);
        make.height.equalTo(@30);
        make.width.equalTo(@52);
        make.top.equalTo(_topView.mas_top).with.offset(25);
    }];
    
    [_backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(_titleLabel.mas_centerY);
        make.height.equalTo(@30);
        make.width.equalTo(@60);
        make.left.equalTo(_topView.mas_left);
    }];
    [_addBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(_titleLabel.mas_centerY);
        make.height.equalTo(@30);
        make.width.equalTo(@42);
         make.right.equalTo(_topView.mas_right).with.offset(-15);
    }];
    [_searchBGLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_topView.mas_left).with.offset(20);
        make.height.equalTo(@32);
        make.right.equalTo(_classifyBtn.mas_left).with.offset(-5);
        make.bottom.equalTo(_topView.mas_bottom).with.offset(-5);
    }];
    [_searchImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_searchBGLabel.mas_left).with.offset(5);
        make.height.equalTo(@30);
        make.width.equalTo(@30);
        make.centerY.equalTo(_searchBGLabel.mas_centerY);
        
    }];
    [_searchTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_searchImageView.mas_right);
        make.height.equalTo(@32);
        make.right.equalTo(_searchBGLabel.mas_right);
        make.centerY.equalTo(_searchBGLabel.mas_centerY);
    }];
    [_classifyBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(_searchBGLabel.mas_centerY);
        make.height.equalTo(@30);
        make.width.equalTo(@60);
        make.right.equalTo(_topView.mas_right).with.offset(-5);
    }];
    
    [_bgImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right) ;
        make.top.equalTo(_topView.mas_bottom);
        make.bottom.equalTo(_totalView.mas_top);
    }];
    [_scanTopView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right) ;
        make.top.equalTo(_topView.mas_bottom);
        make.height.equalTo(@75);
    }];
    [_scanBottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right) ;
        make.bottom.equalTo(self.view.mas_bottom);
        make.height.equalTo(@255);
    }];
    [_ScanLeftView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left);
        make.width.equalTo(@30) ;
        make.bottom.equalTo(_scanBottomView.mas_top);
        make.top.equalTo(_scanTopView.mas_bottom);
    }];
    [_scanRightView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view.mas_right);
        make.width.equalTo(@30) ;
        make.bottom.equalTo(_scanBottomView.mas_top);
        make.top.equalTo(_scanTopView.mas_bottom);
    }];
    [_lineFrameImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_ScanLeftView.mas_right).with.offset(-7);
        make.right.equalTo(_scanRightView.mas_left).with.offset(7);
        make.bottom.equalTo(_scanBottomView.mas_top).with.offset(7);
        make.top.equalTo(_scanTopView.mas_bottom).with.offset(-7);
    }];
    [_lineImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_lineFrameImage.mas_left).with.offset(20);
        make.right.equalTo(_lineFrameImage.mas_right).with.offset(-20);
        make.height.equalTo(@10);
        make.top.equalTo(_lineFrameImage.mas_top);
    }];
    
    
    [_tishiLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_lineFrameImage.mas_left) ;
        make.right.equalTo(_lineFrameImage.mas_right) ;
        make.height.equalTo(@42);
        make.top.equalTo(_topView.mas_top).with.offset(145);
    
        
    }];
   
    
    [_productNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_lineFrameImage.mas_left) ;
        make.right.equalTo(_lineFrameImage.mas_right) ;
        make.height.equalTo(@40);
        make.top.equalTo(_scanBottomView.mas_top).with.offset(30);
        
    }];
    [_specNameLabel1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_lineFrameImage.mas_left) .with.offset(2);
        make.height.equalTo(@12);
        make.top.equalTo(_productNameLabel.mas_bottom).with.offset(2);
        
    }];
    [_specNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_specNameLabel1.mas_right) .with.offset(3);
        make.right.equalTo(_lineFrameImage.mas_right);
        make.height.equalTo(@13);
        make.centerY.equalTo(_specNameLabel1.mas_centerY);
        
    }];
    
    [_countParentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX);
        make.width.equalTo(@200);
        make.height.equalTo(@50);
        make.top.equalTo(_productNameLabel.mas_top).with.offset(90);
        
    }];
    [_subtractCountBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_countParentView.mas_left);
        make.width.equalTo(@50);
        make.top.equalTo(_countParentView.mas_top);
        make.height.equalTo(_countParentView.mas_height);
    }];
    [_countLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(_subtractCountBtn.mas_centerY);
        make.left.equalTo(_subtractCountBtn.mas_right);
        make.height.equalTo(_countParentView.mas_height);
        make.right.equalTo(_addCountBtn.mas_left);
    }];
    [_addCountBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(_countParentView.mas_right);
        make.width.equalTo(@50);
        make.centerY.equalTo(_subtractCountBtn.mas_centerY);
        make.height.equalTo(_countParentView.mas_height);
    }];
    [_totalView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left) ;
        make.right.equalTo(_submitConfirmBtn.mas_left) ;
        make.height.equalTo(@48) ;
        make.bottom.equalTo(self.view.mas_bottom);
    }];
    [_submitConfirmBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view.mas_right) ;
        make.width.equalTo(@160) ;
        make.height.equalTo(@48) ;
        make.bottom.equalTo(self.view.mas_bottom);
    }];
    
    
}
- (IBAction)backAction:(id)sender {
    [self stopReading];
    [_timer invalidate];
    _timer=nil;
    //    NSLog(@"-------%@",scanTypeStr);
    //    if ([scanTypeStr isEqualToString:@""]) {
    //        
    //        
    //    }else{
    [self.navigationController popViewControllerAnimated:YES];
    [[self rdv_tabBarController]setSelectedIndex:0];
    //    }
}

- (void)showAlertMessage:(NSString *)msg
{
    _alt = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:msg delegate:nil cancelButtonTitle:nil otherButtonTitles: nil];
    [_alt show];
    
    [self performSelector:@selector(hideAlert) withObject:nil afterDelay:0.5f];
}
- (void)hideAlert
{
    if (_alt != nil)
    {
        [_alt dismissWithClickedButtonIndex:0 animated:YES];
        _alt = nil;
    }
}
@end
